<template>
  <div class="user-container">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">用户概览</h1>
        <p class="page-description">管理和监控系统用户信息</p>
      </div>
      <div class="page-actions">
        <el-button size="large" @click="exportUserData">
          <el-icon><Download /></el-icon> 导出
        </el-button>
      </div>
    </div>
    
    <!-- 筛选器卡片 -->
    <div class="row-container">
      <el-card class="filter-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span class="card-title">用户筛选</span>
          </div>
        </template>
        <div class="filter-content">
          <div class="filter-item">
            <el-input
              placeholder="搜索用户名或手机号"
              v-model="searchQuery"
              clearable
              class="filter-input"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <div class="filter-actions">
            <el-button @click="resetFilters" size="default">
              <el-icon><Refresh /></el-icon> 重置
            </el-button>
            <el-button type="primary" @click="fetchUsers" size="default">
              <el-icon><Search /></el-icon> 查询
            </el-button>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 用户表格区域 -->
    <div class="row-container">
      <el-card class="table-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <div class="card-title">用户列表</div>
            <div class="bulk-actions" v-if="selectedUsers.length > 0">
              <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
              <el-button type="danger" size="small" @click="bulkDelete">
                <el-icon><Delete /></el-icon> 批量删除
              </el-button>
              <span class="selected-count">已选择 {{ selectedUsers.length }} 项</span>
            </div>
          </div>
        </template>
        
        <el-table
          :data="filteredUsers"
          style="width: 100%"
          v-loading="loading"
          @selection-change="handleSelectionChange"
          :header-cell-style="{backgroundColor: '#f5f7fa', color: '#303133', fontWeight: '600'}"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="user_id" label="用户ID" width="80"></el-table-column>
          <el-table-column prop="user_name" label="用户名"></el-table-column>
          <el-table-column label="手机号码">
            <template #default="scope">
              {{ scope.row.phonenumber || '未设置' }}
            </template>
          </el-table-column>
          <el-table-column prop="register_at" label="注册时间"></el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <div class="action-buttons">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="goToUserDetail(scope.row)">
                  <el-icon><View /></el-icon> 详情
                </el-button>
                <el-button type="danger" size="small" @click="deleteUser(scope.row)">
                  <el-icon><Delete /></el-icon> 删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination">
          <el-pagination
            v-if="pagination"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total">
          </el-pagination>
        </div>
      </el-card>
    </div>
    
    <!-- 浮动操作区 -->
    <div class="floating-actions">
      <el-button type="primary" @click="fetchUsers" :loading="loading" class="refresh-btn">
        <el-icon><RefreshRight /></el-icon>
      </el-button>
    </div>
    
    <!-- 底部安全区域 -->
    <div class="bottom-safe-area"></div>
  </div>
</template>

<script>
import axios from 'axios'
import { Download, Search, Refresh, Delete, View, RefreshRight } from '@element-plus/icons-vue'

export default {
  name: 'UserPage',
  components: {
    Download,
    Search,
    Refresh,
    Delete,
    View,
    RefreshRight
  },
  data() {
    return {
      users: [],
      searchQuery: '',
      currentPage: 1,
      pageSize: 10,
      pagination: null,
      loading: false,
      checkAll: false,
      isIndeterminate: false,
      selectedUsers: []
    }
  },
  created() {
    this.fetchUsers()
  },
  computed: {
    filteredUsers() {
      if (!this.searchQuery) {
        return this.users
      }
      
      const query = this.searchQuery.toLowerCase()
      return this.users.filter(user => 
        (user.user_name && user.user_name.toLowerCase().includes(query)) || 
        (user.phonenumber && user.phonenumber.includes(query))
      )
    }
  },
  methods: {
    fetchUsers() {
      this.loading = true
      axios.get(`https://smartsound.top/api/v1/admin/userdata?size=${this.pageSize}&page=${this.currentPage}`)
        .then(response => {
          if (response.data.code === 0) {
            this.users = response.data.data.users
            this.pagination = {
              page: response.data.data.page,
              size: response.data.data.size,
              total: response.data.data.total,
              total_pages: response.data.data.total_pages
            }
          } else {
            this.$message.error(response.data.message || '获取用户列表失败')
          }
        })
        .catch(error => {
          console.error('获取用户列表出错:', error)
          this.$message.error('获取用户列表失败，请检查网络连接')
        })
        .finally(() => {
          this.loading = false
        })
    },
    resetFilters() {
      this.searchQuery = ''
      this.fetchUsers()
    },
    handleSizeChange(size) {
      this.pageSize = size
      this.fetchUsers()
    },
    handleCurrentChange(page) {
      this.currentPage = page
      this.fetchUsers()
    },
    handleCheckAllChange(val) {
      this.selectedUsers = val ? [...this.users] : []
      this.isIndeterminate = false
    },
    handleSelectionChange(selection) {
      this.selectedUsers = selection
      const selectedCount = selection.length
      this.checkAll = selectedCount === this.users.length && this.users.length > 0
      this.isIndeterminate = selectedCount > 0 && selectedCount < this.users.length
    },
    deleteUser(user) {
      this.$confirm(`确定要删除用户 ${user.user_name} 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用删除用户API，使用DELETE方法
        axios.delete(`https://smartsound.top/api/v1/admin/deleteuser?user_id=${user.user_id}`)
          .then(response => {
            if (response.data.code === 0) {
              const index = this.users.findIndex(u => u.user_id === user.user_id)
              if (index !== -1) {
                this.users.splice(index, 1)
              }
              this.$message.success(response.data.message || '删除成功')
            } else {
              this.$message.error(response.data.message || '删除失败')
            }
          })
          .catch(error => {
            console.error('删除用户出错:', error)
            this.$message.error('删除用户失败，请检查网络连接')
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    bulkDelete() {
      this.$confirm(`确定要删除选中的 ${this.selectedUsers.length} 个用户吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 获取所有选中用户的ID
        const selectedIds = this.selectedUsers.map(user => user.user_id)
        
        // 创建删除请求的Promise数组，使用DELETE方法
        const deletePromises = selectedIds.map(id => 
          axios.delete(`https://smartsound.top/api/v1/admin/deleteuser?user_id=${id}`)
        )
        
        // 并行执行所有删除请求
        Promise.all(deletePromises)
          .then(responses => {
            // 检查所有响应是否成功
            const allSuccess = responses.every(response => response.data.code === 0)
            
            if (allSuccess) {
              // 从用户列表中移除已删除的用户
              this.users = this.users.filter(user => !selectedIds.includes(user.user_id))
              this.$message.success('批量删除成功')
            } else {
              // 部分删除失败
              this.$message.warning('部分用户删除失败，请刷新列表查看最新数据')
              // 刷新用户列表
              this.fetchUsers()
            }
            
            // 清空选中状态
            this.selectedUsers = []
          })
          .catch(error => {
            console.error('批量删除用户出错:', error)
            this.$message.error('批量删除用户失败，请检查网络连接')
            // 刷新用户列表
            this.fetchUsers()
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    exportUserData() {
      this.loading = true
      // 获取所有用户数据（不分页）
      axios.get(`https://smartsound.top/api/v1/admin/userdata?size=1000&page=1`)
        .then(response => {
          if (response.data.code === 0 && response.data.data.users) {
            const users = response.data.data.users
            this.downloadCSV(users)
            this.$message.success('用户数据导出成功')
          } else {
            this.$message.error(response.data.message || '导出用户数据失败')
          }
        })
        .catch(error => {
          console.error('导出用户数据出错:', error)
          this.$message.error('导出用户数据失败，请检查网络连接')
        })
        .finally(() => {
          this.loading = false
        })
    },
    downloadCSV(users) {
      // 定义CSV表头
      const headers = ['用户ID', '用户名', '手机号码', '注册时间']
      
      // 将用户数据转换为CSV行
      const rows = users.map(user => [
        user.user_id,
        user.user_name || '',
        user.phonenumber || '',
        user.register_at || ''
      ])
      
      // 组合表头和数据行
      const csvContent = [
        headers.join(','),
        ...rows.map(row => row.join(','))
      ].join('\n')
      
      // 创建Blob对象
      const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' })
      
      // 创建下载链接
      const link = document.createElement('a')
      const url = URL.createObjectURL(blob)
      
      // 设置下载属性
      const now = new Date()
      const dateStr = `${now.getFullYear()}${(now.getMonth()+1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}`
      const timeStr = `${now.getHours().toString().padStart(2, '0')}${now.getMinutes().toString().padStart(2, '0')}`
      
      link.href = url
      link.setAttribute('download', `用户数据_${dateStr}_${timeStr}.csv`)
      
      // 触发下载
      document.body.appendChild(link)
      link.click()
      
      // 清理
      document.body.removeChild(link)
      URL.revokeObjectURL(url)
    },
    goToUserDetail(user) {
      console.log('Navigating to user detail page with user:', user);
      console.log('User ID:', user.user_id);
      
      if (!user || !user.user_id) {
        this.$message.error('无法查看用户详情：用户ID不存在');
        return;
      }
      
      // 转为字符串类型，确保传递的ID格式正确
      const userId = String(user.user_id);
      console.log('Formatted User ID for navigation:', userId);
      
      this.$router.push({
        name: 'UserDetail',
        params: { id: userId }
      });
    },
  }
}
</script>

<style scoped>
.user-container {
  padding: 16px 5px;
  position: relative;
  margin-bottom: 80px;
}

/* 页面标题区域 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(135deg, #1890ff, #722ed1);
  color: white;
  border-radius: 12px;
  padding: 32px 40px;
  margin-bottom: 35px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  position: relative;
}

.page-header::after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 50%;
  background: rgba(255, 255, 255, 0.1);
  transform: skewX(-20deg);
}

.header-content {
  z-index: 1;
}

.page-title {
  font-size: 28px;
  margin: 0 0 12px 0;
  font-weight: 600;
}

.page-description {
  font-size: 16px;
  margin: 0;
  opacity: 0.9;
  line-height: 1.6;
}

.page-actions {
  z-index: 1;
  display: flex;
  gap: 10px;
}

/* 行容器样式 */
.row-container {
  margin-bottom: 30px;
  position: relative;
  z-index: 0;
}

/* 卡片基本样式 */
.el-card {
  border-radius: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(0, 0, 0, 0.03);
  transform: translate3d(0, 0, 0);
  will-change: transform;
  transition: all 0.3s;
}

.el-card:hover {
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
  z-index: 1;
  border-color: rgba(24, 144, 255, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  margin-right: 12px;
}

/* 筛选器卡片样式 */
.filter-card {
  margin-bottom: 20px;
}

.filter-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
  padding: 0 10px 10px;
}

.filter-item {
  display: flex;
  align-items: center;
  margin-right: 20px;
  margin-bottom: 5px;
}

.filter-input {
  width: 240px;
}

.filter-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 表格卡片样式 */
.table-card {
  margin-bottom: 30px;
}

/* 表格样式 */
.el-table {
  margin: 10px 0;
  border-radius: 8px;
  overflow: hidden;
}

/* 分页控件 */
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 批量操作区域 */
.bulk-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.selected-count {
  color: #606266;
  font-size: 14px;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 8px;
}

/* 按钮样式 */
.el-button {
  border-radius: 4px;
  transition: all 0.3s;
}

.el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 浮动操作区 */
.floating-actions {
  position: fixed;
  right: 24px;
  bottom: 24px;
  display: flex;
  align-items: center;
  z-index: 100;
}

.refresh-btn {
  margin-left: 0;
}

/* 底部安全区域 */
.bottom-safe-area {
  height: 60px;
  width: 100%;
  margin-top: 20px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    padding: 24px;
  }
  
  .page-actions {
    margin-top: 20px;
    flex-wrap: wrap;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .floating-actions {
    right: 16px;
    bottom: 16px;
  }
  
  .filter-content {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-item {
    margin-bottom: 15px;
    width: 100%;
  }
  
  .filter-input {
    width: 100%;
  }
  
  .filter-actions {
    width: 100%;
    justify-content: flex-end;
    margin-top: 10px;
  }
  
  .bulk-actions {
    flex-wrap: wrap;
  }
}
</style>